<template>
  <Modal
    class="lc-modal"
    v-model:visible="visible"
    :footer="false"
    @cancel="cancel"
  >
    <template #title>
      <slot name="title">{{ title }}</slot>
    </template>
    <Form ref="formRef" :model="model" :rules="rules" @submit="submit">
      <slot></slot>
      <slot name="footer">
        <div class="lc-modal-footer">
          <Space>
            <Button @click="cancel">取消</Button>
            <Button html-type="submit" type="primary" :loading="loading"
              >确定</Button
            >
          </Space>
        </div>
      </slot>
    </Form>
  </Modal>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { useVModel } from "@vueuse/core";
import { Modal, Button, Form, Space } from "@arco-design/web-vue";

export default defineComponent({
  components: {
    Modal,
    Button,
    Form,
    Space,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "标题",
    },
    model: {
      type: Object,
      default: () => ({}),
    },
    rules: {
      type: Object,
      default: () => ({}),
    },
    onSunmitOk: {
      type: () => Object,
    },
  },
  emits: ["update:visible", "submit-ok"],
  setup(props, { emit }) {
    const visible = useVModel(props, "visible", emit);
    const formRef = ref<InstanceType<typeof Form>>();
    const loading = ref(false);

    const submit = (data: { values: any; errors: any }) => {
      if (props.onSunmitOk) {
        props.onSunmitOk(data);
      }

      emit("submit-ok", {
        ...data,
        done: (fs = true) => {
          visible.value = !fs;
        },
      });
    };
    const cancel = () => {
      formRef.value?.resetFields();
      visible.value = false;
    };
    return { visible, formRef, submit, cancel, loading };
  },
});
</script>

<style lang="scss" scoped>
.lc-modal-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
